package sms.controller;

import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import sms.entity.User;
import sms.service.UserService;

import java.util.Optional;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 打开登录页面
     * @return 登录页面视图
     */
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    /**
     * 处理登录请求
     * @param username 用户名
     * @param password 密码
     * @param request HttpServletRequest对象
     * @return 登录结果视图
     */
    @PostMapping("/login")
    public ModelAndView processLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();

        // 输入验证
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            modelAndView.addObject("errorMsg", "用户名或密码不能为空");
            modelAndView.setViewName("login");
            return modelAndView;
        }

        User user=userService.login(username, password);
        //登录失败
        if(user==null) {
            modelAndView.addObject("errorMsg", "用户名或密码错误");
            modelAndView.setViewName("login");
            return modelAndView;
        }

        // 登录成功，设置Session
        HttpSession session = request.getSession(true);
        session.setAttribute("loginUser", user);
        session.setMaxInactiveInterval(1800); // 设置Session有效期为30分钟

        //登录成功，重定向到各角色主页
        if(user.getRole().equals("admin")) {
            modelAndView.setViewName("redirect:/admin/index");
        } else if (user.getRole().equals("teacher")) {
            modelAndView.setViewName("redirect:/teacher/index");
        }else {
            modelAndView.setViewName("redirect:/student/index");
        }
        return modelAndView;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }
}